import { ref } from 'vue'
import {
	getUserInfoAPI,
	loginAPI,
	registerAPI,
} from '@/services/login'
import type { LoginParams, RegisterParams, UserTokenInfo } from '../types/login'

// 用户信息状态
const userInfo = ref<UserTokenInfo | null>(null)

// 初始化：从本地存储加载用户信息
const initUserInfo = () => {
	const storedUserInfo = uni.getStorageSync('userInfo')
	if (storedUserInfo) {
		userInfo.value = JSON.parse(storedUserInfo)
	}
}

// 保存用户信息到本地存储
const saveUserInfo = () => {
	if (userInfo.value) {
		uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
	} else {
		uni.removeStorageSync('userInfo')
	}
}

// 登录获取token
const getToken = async (data : LoginParams) => {
	return new Promise((resolve, reject) => {
		loginAPI(data)
			.then((res) => {
				// 合并更新 token 信息，保留原有字段
				const updatedUserInfo : any = {
					access_token: res.data.access_token,
					refresh_token: res.data.refresh_token,
					isLogin: true,
					basicAuth: `Bearer ${res.data.access_token}`,
					avatar: '/admin/sys-file/upms/5c7f4537940744faabe64d17b0be9713.png',
				}
				userInfo.value = updatedUserInfo
				saveUserInfo() // 保存到本地存储
				resolve(res)
			})
			.catch((err) => {
				reject(err)
			})
	})
}

// 查询登录用户信息
const getUserInfos = async () => {
	//查询登录用户
	await getUserInfoAPI().then((res) => {
		// 合并更新 token 信息，保留原有字段
		const updatedUserInfo : any = {
			...userInfo.value,
			userName: res.data.username,
			phone: res.data.phone,
			avatar: res.data.avatar,
			email: res.data.email,
			isLogin: true,
		}
		userInfo.value = updatedUserInfo
		saveUserInfo() // 保存到本地存储
	})
}

// 清理数据
const clearUser = async () => {
	userInfo.value = null
	saveUserInfo() // 清除本地存储
}

// 注册用户
const registerUser = async (data : RegisterParams) => {
	return new Promise((resolve, reject) => {
		registerAPI(data)
			.then((res) => {
				uni.showToast({
					title: '注册成功',
					icon: 'success'
				})
			})
			.catch((err) => {
				reject(err)
			})
	})
}

// 初始化用户信息
initUserInfo()

// 导出状态和方法
export {
	userInfo,
	getToken,
	clearUser,
	registerUser,
	getUserInfos
}